use crate::configuration;
use crate::db::config::Protocol;
use sea_orm::{ConnectOptions, Database, DatabaseConnection};
use std::sync::LazyLock;
use std::time::Duration;

/// 创建数据库连接
async fn get_connect() -> DatabaseConnection {

    let database = configuration::database();
    let url = database.url();
    let mut opt = if url.is_some() {
        ConnectOptions::new(url.unwrap())
    } else {
        let db = database.protocol();
        let protocol = db.to_string();
        let username = database.username();
        let password = database.password();
        let host = database.host();
        let port = database.port();
        let schema = database.schema();
        let database = database.database();
        let format = format!(
            "{}://{}:{}@{}:{}/{}",
            protocol, username, password, host, port, database,
        );
        if let Protocol::Postgres = db {
            ConnectOptions::new(format!("{}?currentSchema={}", format, schema))
        } else {
            ConnectOptions::new(format)
        }
    };

    opt.max_connections(database.max_connections())
        .min_connections(database.min_connections())
        .connect_timeout(Duration::from_secs(database.connect_timeout() as u64))
        .idle_timeout(Duration::from_secs(database.idle_timeout() as u64))
        .sqlx_logging(database.enable_logging());
        // .sqlx_logging_level(log::LevelFilter::Debug);
    let db = Database::connect(opt).await.expect("数据库连接失败");
    match db.ping().await {
        Ok(_) => log::info!("数据库连接成功"),
        Err(e) => panic!("数据库连接失败: {}", e),
    }
    db
}

static CONNECT: LazyLock<DatabaseConnection> =
    LazyLock::new(|| futures_lite::future::block_on(get_connect()));

/// 获取数据库连接
pub fn get() -> &'static DatabaseConnection {
    &CONNECT
}
